package model;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JOptionPane;

/**
 * The FileManager class is responsible for serializing objects to files and
 * de-serializing them from files
 *
 * @author Kevin
 * @version 2014-05-17
 */
public class FileManager {

    /**
     * Serializes an object and stores it as a file
     *
     * @param object The object to be Serialized
     * @param filename File to save the object to
     * @return true or false
     */
    public boolean writeToFile(Object object, String filename) {
        try (FileOutputStream fout = new FileOutputStream("data\\" + filename)) {
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(object);
            oos.close();
            return true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Data kunde inte sparas", "Felmeddelande", JOptionPane.ERROR_MESSAGE);
            System.err.println(ex);
            return false;
        }
    }

    /**
     * De-serializes files
     *
     * @param filename the name of the file we are going to deSerialize
     * @return deSerialized file
     */
    public Object readFile(String filename) {
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data\\" + filename));
            return ois.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "Kunde inte ladda data", "Felmeddelande", JOptionPane.ERROR_MESSAGE);
            System.err.println(ex);
            return null;
        }
    }
}
